今日將Day23 Servlet - Project專案將它改寫為Spring MVC版本
(1) 請參考Day27 module
(2) 使用JSON相關設置請參考Day29
(3) 參考Day23 project,將servlet package重寫並將對應Service與Dao改寫
springmvc-servlet.xml
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/static/"/>
<property name="suffix" value=".html"/>
</bean>
創建Controller package取代原先servlet package
創建RootController導向靜態頁面
@Controller
public class RootController {
@GetMapping("/")
public String index(){
System.out.println("hello index");
return "index";
}
@GetMapping("crud")
public String crud(){
System.out.println("hello crud");
return "crud";
}
}
@RestController
@RequestMapping("/api/employees")
public class EmpController extends HttpServlet {
private EmployeeService employeeService;
@Autowired
public EmpController(EmployeeService employeeService) {
this.employeeService =employeeService;
}
@GetMapping
protected Result<List<Employee>> readEmps() {
List<Employee> employees = employeeService.getAllEmployees();
Result<List<Employee>> result = new Result<>(true, "Employees fetched successfully", employees);
return result;
}
@PostMapping
protected Result createEmp(@RequestBody Employee employee) {
employeeService.createEmployee(employee);
Result result = new Result(true, "Employee saved successfully");
return result;
}
@PutMapping(path = "/{empId}")
protected Result updateEmp(@RequestBody Employee employee,@PathVariable("empId") String empId){
boolean isSuccess = employeeService.updateEmployee(Integer.parseInt(empId), employee);
String message = isSuccess?"Employee updated successfully":"Employee update failed";
Result result = new Result(isSuccess, message);
return result;
}
@DeleteMapping(path = "/{empId}")
public Result deleteEmp(@PathVariable("empId") String empId){
boolean isSuccess = employeeService.deleteEmployee(Integer.parseInt(empId));
String message = isSuccess?"Employee deleted successfully":"Employee deleted failed";
Result result = new Result(isSuccess, message);
return result;
}
}
僅修改login方法
@PostMapping("login")
public void login(HttpServletResponse response,@RequestBody User user){
Result result = new Result();
if (authenticate(user)) {
// 創建token
String token = JwtUtils.createToken(user.getUsername());
System.out.println(token);
// 設置 Cookie
Cookie jwtCookie = new Cookie("token", token);
jwtCookie.setHttpOnly(true); // 防止 JavaScript 存取,減少 XSS 攻擊風險
jwtCookie.setPath("/");
jwtCookie.setMaxAge(24 * 60 * 60); // 1 天
response.addCookie(jwtCookie);
result.setSuccess(true);
result.setMessage("Login successful!");
} else {
// 如果驗證失敗
result.setSuccess(false);
result.setMessage("Invalid username or password.");
}
JsonUtils.writeJson(response,result);
}
@Component
public class EmployeeDao {
//略
}
修改EmployeeService層annotation
@Service
public class EmployeeService {
private EmployeeDao employeeDao;
@Autowired
public EmployeeService(EmployeeDao employeeDao) {
this.employeeDao = employeeDao;
}
//其他略
}